//
//  JJChatBar.swift
//  swiftProject
//
//  Created by yangjian on 2021/12/12.
//

import UIKit
import CoreAudio
import RxSwift
enum JJChatBarPanelType{
    case none
    case systemKeyboard
    case voice
    case emoji
    case functions
}

protocol JJChatBarDelegate:NSObjectProtocol {
    func panelChanged(oldType:JJChatBarPanelType,newType:JJChatBarPanelType)
}

let chatBar_textFont = UIFont.systemFont(ofSize: 18, weight: .regular)
//let chatBar_height = 50

class JJChatBar: UIView {
    
    typealias TextViewWillChangeCallBack = (UITextView,NSRange,String) -> Bool
    var textWillChangeCallBack : TextViewWillChangeCallBack = {_,_,_ in true}
    let rx_panelChanged = PublishSubject<(JJChatBarPanelType,JJChatBarPanelType)>()
    let rx_textHeightChanged = PublishSubject<CGFloat>()
    let bag = DisposeBag()
    
    var currentTextHeight:CGFloat = 26
//    let contentHeight:Int = 40
    let voiceButton = UIButton(type: .custom)
    let emojiButton = UIButton(type: .custom)
    let functionsButton = UIButton(type: .custom)
    let textViewBgView = UIView()
    let textView = UITextView()
    let atHelper = IMChatBarMsgAtHelper()
    var currentPanelType = JJChatBarPanelType.none
    weak var delegate : JJChatBarDelegate?
//    weak var chatHelper : JJSingleChatHelper?
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.config()
    }
    init() {
        super.init(frame: CGRect.zero)
        self.config()
    }
    
    func config(){
        configUI()
        configCallBack()
    }
    
    func configUI(){
        
        let topLine = UIView()
        topLine.backgroundColor = UIColor.lightGray
        self.addSubview(topLine)
        let bottomLine = UIView()
        bottomLine.backgroundColor = UIColor.lightGray
        self.addSubview(bottomLine)
        topLine.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(0.6)
        }
        bottomLine.snp.makeConstraints { make in
            make.bottom.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(0.6)
        }

        self.addSubview(voiceButton)
        self.addSubview(emojiButton)
        self.addSubview(functionsButton)
        self.addSubview(textViewBgView)
        textViewBgView.addSubview(textView)

        voiceButton.setImage(UIImage.init(named: "chatbar_icon_voice"), for: .normal)
        voiceButton.setImage(UIImage.init(named: "chatbar_icon_keyboard"), for: .selected)
        voiceButton.addTarget(self, action: #selector(voiceButtonClick(sender:)), for: .touchUpInside)
        voiceButton.snp.makeConstraints { make in
            make.left.equalTo(5)
            make.bottom.equalTo(0)
            make.size.equalTo(CGSize(width: 40, height: 50))
        }
                
        functionsButton.setImage(UIImage.init(named: "chatbar_icon_functions"), for: .normal)
        functionsButton.addTarget(self, action: #selector(functionsButtonClick(sender:)), for: .touchUpInside)
        functionsButton.snp.makeConstraints { make in
            make.right.equalTo(-5)
            make.bottom.equalTo(0)
            make.size.equalTo(CGSize(width: 40, height: 50))
        }

        emojiButton.setImage(UIImage.init(named: "chatbar_icon_emoji"), for: .normal)
        emojiButton.setImage(UIImage.init(named: "chatbar_icon_keyboard"), for: .selected)
        emojiButton.addTarget(self, action: #selector(emojiButtonClick(sender:)), for: .touchUpInside)
        emojiButton.snp.makeConstraints { make in
            make.right.equalTo(functionsButton.snp.left)
            make.bottom.equalTo(0)
            make.size.equalTo(CGSize(width: 40, height: 50))
        }
        
        
        
        textViewBgView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(50)
            make.bottom.equalTo(-8)
            make.right.equalTo(-90)
        }
        self.textView.snp.makeConstraints { make in
            make.top.equalTo(4)
            make.left.equalTo(4)
            make.bottom.equalTo(-4)
            make.right.equalTo(-4)
            make.height.equalTo(self.currentTextHeight)
        }

        textViewBgView.backgroundColor = UIColor.white
        textViewBgView.layer.cornerRadius = 6
        textViewBgView.layer.masksToBounds = true
        textViewBgView.layer.borderWidth = 0.4
        textViewBgView.layer.borderColor = UIColor.lightGray.cgColor
        
        self.textView.textContainer.lineFragmentPadding = 0
        self.textView.returnKeyType = UIReturnKeyType.send
        self.textView.delegate = self
//        let topANDbottom = (40 - chatBar_textFont.lineHeight) / 2 / 2
//        let leftANDright:CGFloat = 4
        self.textView.textContainerInset
        // = UIEdgeInsets.zero
        = UIEdgeInsets(top: 2, left: 2,
                       bottom: 2, right: 2)
        self.textView.typingAttributes = chatBarTextAttributes
        
        self.voiceButton.backgroundColor = UIColor.orange
        self.functionsButton.backgroundColor = UIColor.orange
        self.emojiButton.backgroundColor = UIColor.orange
        
    }
    
    func configCallBack(){
        self.textView.rx.text.subscribe {[unowned self] text in
            
            var textHeight = fitHeight_attributedString(attributedString: self.textView.attributedText, maxWidth:screen_width() - 156)
            if textHeight > 100 {
                textHeight = 100
            }
            if textHeight < 26 {
                textHeight = 26
            }
            if textHeight == currentTextHeight {
                return
            }
            self.textView.snp.updateConstraints { make in
                make.height.equalTo(textHeight)
            }
            self.textView.layoutIfNeeded()
            if textHeight > currentTextHeight {
                self.rx_textHeightChanged.onNext(textHeight)
            }
            currentTextHeight = textHeight
//            UIView.animate(withDuration: 0.2) {[unowned self] in
//            }completion: {[unowned self] finished in
//            }
        }.disposed(by: bag)
    }
}


//buttonClick
extension JJChatBar{
    @objc func voiceButtonClick(sender : UIButton){
        var newPanelType = JJChatBarPanelType.none
        if sender.isSelected {
//            sender.isSelected = false
            newPanelType = .systemKeyboard
        }else {
            sender.isSelected = true
            self.emojiButton.isSelected = false
            self.functionsButton.isSelected = false
            newPanelType = .voice
        }
        print(sender.isSelected)
        print(self.currentPanelType)
        print(newPanelType)
        rx_panelChanged.onNext((self.currentPanelType, newPanelType))
        self.currentPanelType = newPanelType
    }
    @objc func emojiButtonClick(sender : UIButton){
        var newPanelType = JJChatBarPanelType.none
        if sender.isSelected {
//            sender.isSelected = false
            newPanelType = .systemKeyboard
        }else {
            sender.isSelected = true
            self.voiceButton.isSelected = false
            self.functionsButton.isSelected = false
            newPanelType = .emoji
        }
        rx_panelChanged.onNext((self.currentPanelType, newPanelType))
        self.currentPanelType = newPanelType

    }
    @objc func functionsButtonClick(sender : UIButton){
        var newPanelType = JJChatBarPanelType.none
        if sender.isSelected {
//            sender.isSelected = false
            newPanelType = .systemKeyboard
        }else {
            sender.isSelected = true        
            self.voiceButton.isSelected = false
            self.emojiButton.isSelected = false
            newPanelType = .functions
        }
        rx_panelChanged.onNext((self.currentPanelType, newPanelType))
        self.currentPanelType = newPanelType
    }
}

extension JJChatBar {
    
    func didShowSystemKeyborad() {
        self.voiceButton.isSelected = false
        self.emojiButton.isSelected = false
        self.functionsButton.isSelected = false
        self.currentPanelType = .systemKeyboard
    }
    
    func hideAllPanel(){
        if self.currentPanelType == .none{
            return
        }
        self.voiceButton.isSelected = false
        self.emojiButton.isSelected = false
        self.functionsButton.isSelected = false
        rx_panelChanged.onNext((self.currentPanelType, .none))
        self.currentPanelType = .none
    }
    
    //在将要离开界面的时候调用这里(需要对键盘做额外的操作,否则会产生各种怪异的效果,虽然最终结果没什么问题)
    func hideAllPanelExceptionSystemKeyboard(){
        self.voiceButton.isSelected = false
        self.emojiButton.isSelected = false
        self.functionsButton.isSelected = false
        if self.currentPanelType == .systemKeyboard {
            self.currentPanelType = .systemKeyboard
        }else{
            rx_panelChanged.onNext((self.currentPanelType, .none))
            self.currentPanelType = .none
        }
    }
    
    func sendTextMessage(){
        
        
//        let message =
//        EMChatMessage.init(conversationID: self.chatHelper!.conversation.conversationId, from: EMClient.shared().currentUsername!, to: self.chatHelper!.conversation.conversationId, body: body, ext: messageExt)
//        message.chatType = EMChatType.groupChat
//        guard let message = message else {
//            print("消息创建失败,未知错误!!!")
//            return
//        }
//        JJChatService.shared().sendMessage(message: message) { p in
//        } completion: { resultMsg, error in
//        }
        self.atHelper.atters.removeAll()
        self.textView.text = ""
    }

}

extension JJChatBar:UITextViewDelegate {
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        return textWillChangeCallBack(textView, range, text)
    }
}


